﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Useful
{
    public class BooleanTypeConverter : BooleanConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
        {
            if (value != null && value != DBNull.Value)
            {
                if (value is bool)
                {
                    return (bool)value ? "Да" : "Нет";
                }
                else
                {
                    string str = value.ToString().ToLower();

                    if (str == "true")
                        return "Да";
                    else if (str == "false")
                        return "Нет";
                    else
                        return "---";
                }
            }
            else
                return "---";
        }

        //TODO Если null?
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string str = (string)value;

            if (str == "Да")
                return true;
            else if (str == "Нет")
                return false;
            else
                return null;

            //return (string)value == "Да";
        }
    }

    public class MyDateTimeTypeConverter : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
        {
            if (value != null && value != DBNull.Value)
            {
                if (value is DateTime)
                {
                    return ((DateTime)value).ToString("dd.MM.yyyy HH:mm");
                }
                else
                {
                    return DateTime.Parse(value.ToString()).ToString("dd.MM.yyyy HH:mm"); // TODO Не тестировал
                }
            }
            else
                return "---"; // TODO Не тестировал
        }

        // TODO Не тестировал
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string str = (string)value;

            DateTime? res;

            if (str != "---")
            {
                DateTime val;

                if (DateTime.TryParse(str, out val))
                    res = val;
                else
                    throw new Exception();
            }
            else
                res = null;

            return res;
        }
    }
}
